package com.example.netty.netty.HTTPExample;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

//通讯数据会被封装成 httpObject
public class HTTPServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    //有读取事件时触发
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        if (httpObject instanceof HttpRequest) {
            //在同一个bossGroup中每个浏览器对应一个workerGroup，但如果有多个bossGroup进行轮询就不会有对应关系
            System.out.println("handler hashcode:"+this.hashCode()+
                    ",pipLine hashCode:"+channelHandlerContext.channel().pipeline().hashCode());
            System.out.println("消息类型："+httpObject.getClass());
            System.out.println("clientAddress："+channelHandlerContext.channel().remoteAddress());
            //过滤特定请求路径
            HttpRequest httpRequest = (HttpRequest) httpObject;
            URI uri = new URI(httpRequest.uri());
            if (uri.getPath().equals("/favicon.ico")) {
                System.out.println("请求favicon.ico，不做响应");
                return;
            }

            //模拟长轮询，hold住消息10秒后再应答客户端(客户端可以后台异步进行长轮询)
            Thread.sleep(1000*10);

            //回复消息
            ByteBuf buf = Unpooled.copiedBuffer("hello,httpClient....", CharsetUtil.UTF_8);
            //构造一个http响应
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,buf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8")
                    .set(HttpHeaderNames.CONTENT_LENGTH,buf.readableBytes());
            channelHandlerContext.writeAndFlush(response);
        }
    }
}
